package view.completeView;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;

import javax.swing.JPanel;

import program.ExperimentManager;

import reference.constants.ConstantProblem;

import utilities.view.PanelBuffer;
import view.completeView.entityView.EntityView;
import view.completeView.groundView.GroundView;

import controller.entitiesManagement.EntitiesManagement;
import controller.entitiesManagement.Entity;
import controller.environment.GroundManager;
import controller.environment.ground.Ground;

public class CompletePanel extends JPanel implements GroundManagerListener {
	
	private static final long serialVersionUID = -7739727656756286717L;
	private GroundView[][] m_grounds;
	private ArrayList<EntityView> m_entities;

	public CompletePanel(CompleteFrame frame, ExperimentManager experiment_manager){
		super();
		this.setBounds(0, 0, frame.getWidth(), frame.getHeight());
		this.setBackground(Color.BLACK);
		GroundManager groundManager = GroundManager.getInstance();
		m_entities = new ArrayList<EntityView>();
		createGroundView(groundManager);
		groundManager.addListener(this);
		createEntityView(EntitiesManagement.getInstance().getEntities());
		this.repaint();
	}

	public void changeGround(Ground ground, int pos_x, int pos_y) {
		m_grounds[pos_x][pos_y] = null;
		m_grounds[pos_x][pos_y] = new GroundView(ground);
		this.repaint();
	}
	
	private void createGroundView(GroundManager ground_manager){
		m_grounds = new GroundView[ConstantProblem.GROUND_WIDTH][ConstantProblem.GROUND_HEIGHT];
		for(int i=0;i<ConstantProblem.GROUND_WIDTH;i++){
			for(int j=0;j<ConstantProblem.GROUND_HEIGHT;j++){
				m_grounds[i][j] = new GroundView(ground_manager.getGround(i, j));
			}
		}
	}
	
	private void createEntityView(ArrayList<Entity> entities){
		for(Entity entity : entities){
			m_entities.add(new EntityView(this, entity));
		}
	}
	
	public void paint(Graphics g){
		PanelBuffer buffer = new PanelBuffer(this.getWidth(), this.getHeight());
		for(int i=0;i<ConstantProblem.GROUND_WIDTH;i++){
			for(int j=0;j<ConstantProblem.GROUND_HEIGHT;j++){
				if(m_grounds[i][j]!=null)
					m_grounds[i][j].paint(buffer);
			}
		}
		for(EntityView entityView : m_entities){
			entityView.paint(buffer);
		}
		g.drawImage(buffer, 0, 0, this);
	}
}
